<template>
	<view class="page">
		<view class="mpopup">
			<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
				<view @click="openSelector">
					<mpopupHeaderRadioItem label="申请人名称" :value="selectedRow.operatorName || '[修改]'" height="60px">

					</mpopupHeaderRadioItem>
					<mpopupHeaderRadioItem label="受理号" :value="selectedRow.acceptNumber || '[修改]'" height="60px" />
					<mpopupHeaderRadioItem label="申请事项" :value="findTextByValue(selectedRow.bidType) || '[修改]'"
						height="60px" />
					<mpopupHeaderRadioItem label="主题业态" :value="findLabelByValue(selectedRow.businessFormat) || '[修改]'"
						height="60px" />
					<mpopupHeaderRadioItem label="经营项目"
						:value="findLabelByValue2(selectedRow.businessProject) || '[修改]'" height="60px" />
					<mpopupHeaderRadioItem label="现场核查人员" :value="selectedRow.checkPersonnelSignOne || '[修改]'"
						height="60px" />
					<mpopupHeaderRadioItem label="现场核查日期" :value="selectedRow.checkSignDateOne || '[修改]'"
						height="60px" />

				</view>
				<mpopupHeaderRadioItem label="材料审查情况" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list'
						v-model="selectedRow.reviewStatus" @change="formatRadiochange"
						:localdata="valueOptions"></uni-data-checkbox>
				</mpopupHeaderRadioItem>
				<mpopupHeaderRadioItem label="现场核查情况" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<!-- 自定义右侧内容 -->
					<template #default="{ value }">
						<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list'
							v-model="selectedRow.verificationSituation" @change="onCheckboxChange"
							:localdata="valueOptions2"></uni-data-checkbox>
					</template>
				</mpopupHeaderRadioItem>
				<mpopupHeaderRadioItem :value="selectedRow.remark" label="综合评审意见" :custom-class="'custom-align'"
					:show-bottom-border="true" :custom-style="{ padding: '20rpx' }">
				</mpopupHeaderRadioItem>
			</uni-card>
			<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<uni-title type="h1" title="相关人员/单位签字盖章" align="center"></uni-title>
			<!-- 签名区块组件 -->
			<view class="signature-container">

				<SignatureBlock label="经办人签名" :sign-image.sync="selectedRow.checkPersonnelSign"
					:date.sync="selectedRow.checkSignDate" />

				<SignatureBlock label="复核人签名" :sign-image.sync="selectedRow.foodPersonSign"
					:date.sync="selectedRow.foodPersonDate" />

				<SignatureBlock label="中心负责人签名" :sign-image.sync="selectedRow.centerPersonSign"
					:date.sync="selectedRow.centerPersonDate" />

				
			</view>
			</uni-card>
			<view v-show="editStatus!='FALSE'">
				<!-- 签章区域 -->
				<button type="primary" style="margin-top: 15px;" @click="submitForm('1')">保存并提交技术评审报告</button>
				<button type="primary" style="margin-top: 10px;" @click="submitForm('0')">暂存</button>
			</view>
		</view>
		<enterpriseSelector tableType="1" :query="{orderType: '1', auditStatus: '1' }" type="radio" ref="selector"
			:multiple="false" @confirm="handleConfirm" @close="handleClose" />

		<!-- 添加日期选择弹窗 -->
		<uni-popup ref="datePopup" type="dialog">
			<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
				<uni-datetime-picker type="date" @change="handleDateChange" />
			</uni-popup-dialog>
		</uni-popup>
	</view>


</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import enterpriseSelector from '@/components/dialog/enterprise-dialog.vue'
	import SignatureBlock from '@/components/signature/signature.vue'

	import {
		categoryInfo,
		addCategory,
		categoryUpdate,
		getCateGoryList,
		getMedicalDict,
		workOrderInfo,
	} from '@/api/order'
	export default {
		name: "xlh-table",
		components: {
			signInput,
			mpopupHeaderRadioItem,
			mpopupHeaderItem, // 需先导入组件
			enterpriseSelector,
			SignatureBlock
		},
		onLoad(options) {

			if (options.editStatus != null) {

				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);
				this.workOrderId = workOrderId;
				this.editStatus = editStatus;
				this.getcategoryInfo(workOrderId);

			} else {
				const orderid = decodeURIComponent(options.workOrderId);
				this.workOrderId = orderid;
				console.log(this.workOrderId)
				//材料审查情况
				this.getMedicalDict('material_audit_status'),
					//现场核查情况	
					this.getMedicalDict('scene_check_status')
				this.getMedicalDict('order_type')
				this.getMedicalDict('mode_of_operation')
				this.getMedicalDict('bid_type')
				this.getMedicalDict('business_project'),
					this.getMedicalDict('business_format')
			}

		},

		data() {
			return {
				searchText: '',
				workOrderId: '',
				currentDate: '',
				tableData: [],
				// 分页控制参数
				pageSize: 10, // 保持固定值
				total: 0, // 总数据量
				currentPage: 1, // 当前页码（建议更名更清晰）
				selectedRow: {
					checkPersonnelSignOne: '',
					checkSignDateOne: '',
					foodPersonSign: '',
					centerPersonSign: '',
					reviewOpinions: '',
					checkCount: 0, // 替换检查项目数
					checkNoConform: 0,
					operatorName: '',
					address: '',
					acceptNumber: '',
					bidType: '',
					businessFormat: '',
					businessProject: '',
					checkOpinion: 0,
					auditStatus: 0,
					workOrderId: '',
				}, // 存储选中行数据

				editStatus: 'ADD',
				auditStatusMap: {
					'0': '未完成',
					'1': '已完成'
				},
				radio1: 0,
				radio2: 0,
				valueOptions: [],
				valueOptions2: [],
				projectItem: {},
				formatItem: {},
				checkBoxIndex: 0,
				remarkDialog: '',
				bidTypeItem: {},
			}
		},
		methods: {
			// 打开选择器
			openSelector() {
				this.$refs.selector.open()
			},
			// 获取工单详情
			async getcategoryInfo(orderId) {
				const res = await categoryInfo(orderId);
				if (res.code === 0) {
					this.selectedRow = res.data;
					//材料审查情况
					this.getMedicalDict('material_audit_status'),
						//现场核查情况	
					await this.getMedicalDict('scene_check_status')
					await this.getMedicalDict('order_type')
					await this.getMedicalDict('mode_of_operation')
					await this.getMedicalDict('bid_type')
					await this.getMedicalDict('business_project'),
					await this.getMedicalDict('business_format')
				}
			},

			// 提交方法
			async submitForm(status) {
				
				this.selectedRow.workOrderId = this.workOrderId;
				
				try {
					// 状态校验前置
					if (this.editStatus === 'FALSE') {
						return uni.showToast({
							title: '当前处于查看状态',
							icon: 'none'
						});
					}
					// 统一处理提交逻辑
					const isEditMode = this.editStatus === 'EDIT';
					const apiMethod = isEditMode ? categoryUpdate : addCategory;
					// 构造请求参数（避免污染原始数据）
					const payload = {
						...this.selectedRow,
						auditStatus: status,
					};

					// 显示加载状态
					uni.showLoading({
						title: '提交中...',
						mask: true
					});

					// 执行API调用
					const res = await apiMethod(payload);

					if (res.code !== 0) {
						throw new Error(res.msg || '服务器处理异常');
					}

					// 统一处理成功逻辑
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});

	// 关闭当前页面，跳转到工单页
		this.$closeAndRedirect({
		  url: '/pages/work/history/index'
		});

				} catch (error) {
					// 统一错误处理
					console.error('提交失败:', error);
					uni.showToast({
						title: error.msg || '请求失败，请检查网络',
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
				}
			},



			handleConfirm(e) {
				this.selectedRow = e;
			},
			handleClose() {

			},

			hasOrgName(info) {
				return info.some(item => item && item.orgName);
			},
			hasSpecialOrgName(info) {
				return info.some(item => item && item.orgName === "材料审查情况");
			},
			handleSign(type) {
				uni.chooseImage({
					success: res => {
						console.log(`${type}签名更新:`, res.tempFilePaths)
					}
				})
			},
			handleDateEdit(type, unit) {
				uni.showModal({
					title: `编辑${unit}`,
					content: `请输入${type}的${unit}份`,
					success: (res) => {
						if (res.confirm) {
							console.log(`${type} ${unit}更新为:`, res.content)
						}
					}
				})
			},
			handleStamp() {
				uni.chooseImage({
					success: res => {
						console.log('公章更新:', res.tempFilePaths)
					}
				})
			},
			// 修改分页处理方法
			handlePageChange(e) {
				// uni-pagination的事件参数在e.detail
				console.log('分页事件:', e);
				this.currentPage = e.detail.current;
				this.getCateGoryListApi();
			},
			// 迭代方式查找（推荐）
			findLabelByValue(targetValue) {
				// 判断是否为整数（支持数值型或字符串型整数）
				const isIntegerValue = (val) => {
					if (typeof val === 'number') {
						return Number.isInteger(val); // 数值型整数检测
					} else if (typeof val === 'string') {
						return /^-?\d+$/.test(val.trim()); // 字符串型整数检测（如 "123"）
					}
					return false; // 其他类型直接返回 false
				};

				// 非整数直接返回原值
				if (!isIntegerValue(targetValue)) {
					return targetValue;
				}
				const queue = [...this.formatItem] // 创建队列初始化数据

				while (queue.length > 0) {
					const item = queue.shift() // 取出队列第一个元素

					if (item.value === targetValue) {
						return item.label // 找到目标立即返回
					}

					// 将子节点加入队列继续搜索
					if (item.children?.length) {
						queue.push(...item.children)
					}
				}

				return '' // 未找到
			},
			// 新增行点击方法
			handleRowClick(row) {
				this.selectedRow = row;
				this.$refs.table.setSelection([row.uniqueId]);
			},
			// 迭代方式查找（推荐）
			findLabelByValue2(targetValue) {
				// 判断是否为整数（支持数值型或字符串型整数）
				const isIntegerValue = (val) => {
					if (typeof val === 'number') {
						return Number.isInteger(val); // 数值型整数检测
					} else if (typeof val === 'string') {
						return /^-?\d+$/.test(val.trim()); // 字符串型整数检测（如 "123"）
					}
					return false; // 其他类型直接返回 false
				};

				// 非整数直接返回原值
				if (!isIntegerValue(targetValue)) {
					return targetValue;
				}
				const queue = [...this.projectItem] // 创建队列初始化数据

				while (queue.length > 0) {
					const item = queue.shift() // 取出队列第一个元素

					if (item.value === targetValue) {
						return item.label // 找到目标立即返回
					}

					// 将子节点加入队列继续搜索
					if (item.children?.length) {
						queue.push(...item.children)
					}
				}

				return '' // 未找到
			},
			findTextByValue(value) {

				// 判断是否为整数（支持数值型或字符串型整数）
				const isIntegerValue = (val) => {
					if (typeof val === 'number') {
						return Number.isInteger(val); // 数值型整数检测
					} else if (typeof val === 'string') {
						return /^-?\d+$/.test(val.trim()); // 字符串型整数检测（如 "123"）
					}
					return false; // 其他类型直接返回 false
				};

				// 非整数直接返回原值
				if (!isIntegerValue(value)) {
					return value;
				}

				const item = this.bidTypeItem.find(item => item.value === value);
				return item ? item.text : '';

			},

			handleSearchInput() {
				this.currentPage = 1;
				this.getCateGoryListApi();
			},
			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)
					// 增加响应状态判断
					if (res.code === 0) {

						if (type === 'material_audit_status') {
							this.valueOptions = res.data.map(item => ({
								text: item.label, // 注意字段名需与uni-data-select要求一致
								value: item.value
							}))
						} else if (type === 'scene_check_status') {


							const res = await getMedicalDict(type)
							if (res.code === 0) {
								// 使用全新数组赋值（核心）
								this.valueOptions2 = res.data
									.map((item, index, arr) => {
										if (index === 0) {
											return {
												text: item.label
													.replace(/{{checkCount}}/g, '0')
													.replace(/{{checkNoConform}}/g, '0'),
												value: item.value
											}
										}
										if (index === 1) {
											const nextItem = arr[2]
											return {
												text: [
													item.label,
													//'_________',
													this.selectedRow.reviewOpinions?.trim() || '————',
													nextItem.label
												].join(' '),
												value: item.value
											}
										}
										return null
									})
									.filter(Boolean) // 清除空项

								// 强制更新机制
								this.$nextTick(() => {
									this.refreshKey++ // 触发组件重新渲染
								})
							}
							
						} else if (type === 'bid_type') { //申办类型
							this.bidTypeItem = res.data.map(item => ({
								text: item.label,
								value: item.value
							}))

						}
						if (type === 'business_project') {
							this.projectItem = res.data.map(item => ({
								label: item.label,
								value: item.value,
								remark: item.remark
							}));
							// 并发获取二级数据
							this.projectItem = await Promise.all(
								this.projectItem.map(async item => {
									if (item.remark) {
										try {
											const subData = await getMedicalDict(item.remark)
											return {
												...item,
												children: subData.data
											}
										} catch (e) {
											console.error('子接口请求失败', e)
											return {
												...item,
												children: []
											} // 失败时保留父级数据
										}
									}
									return item
								})
							)
						} else if (type === 'business_format') {
							// 格式化数据结构
							this.formatItem = res.data.map(item => ({
								label: item.label,
								value: item.value,
								remark: item.remark
							}));

							// 并发获取二级数据
							this.formatItem = await Promise.all(
								this.formatItem.map(async item => {
									if (item.remark) {
										try {
											const subData = await getMedicalDict(item.remark)
											return {
												...item,
												children: subData.data
											}
										} catch (e) {
											console.error('子接口请求失败', e)
											return {
												...item,
												children: []
											} // 失败时保留父级数据
										}
									}
									return item
								})
							)
						}

					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取失败',
						icon: 'none',
						duration: 2000
					})
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.container-bottom {
		margin-top: 10px;
		display: flex;
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}


	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}


	
	// 弹窗容器样式
	.custom-popup {
		width: auto !important;
		/* 自适应宽度 */
		min-width: 300px;
		max-width: 80%;
		border-radius: 8px;

		/* 按钮容器 */
		.dialog-buttons {
			display: flex;
			justify-content: flex-end;
			gap: 10px;
			margin-top: 20px;
		}

		/* 取消按钮 */
		.cancel-btn {
			background-color: #f0f0f0 !important;
			color: #666 !important;
		}

		/* 确定按钮 */
		.confirm-btn {
			background-color: #2979ff !important;
			color: white !important;
		}




		// 内容区域适配
		.dialog-container {
			padding: 30px;
			max-height: 80vh; // 控制最大高度
			overflow-y: auto;
			border-radius: 10px;

			.uni-container {
				width: 100%;

				// 表格适配
				uni-table {
					width: 100%;

					// 单元格内容换行
					uni-td,
					uni-th {
						white-space: normal !important;
						word-break: break-word;
						padding: 8px 12px;
					}
				}

				// 分页器适配
				.uni-pagination-box {
					margin-top: 15px;
					padding: 0 10px;
				}
			}
		}
	}

	// 新增响应式处理
	@media (max-width: 768px) {
		.custom-popup {
			width: 90% !important;
			max-width: none;

			.dialog-container {
				padding: 15px;

				uni-table {
					font-size: 14px;

					uni-td,
					uni-th {
						padding: 6px 8px;
					}
				}
			}
		}
	}

	/* 新增搜索框样式 */
	.search-input {
		margin-bottom: 20px;

		/deep/ .uni-easyinput__content {
			border-radius: 15px;
			padding: 0 15px;
		}
	}

	.custom-title {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10px;
		/* 保持原有下边距 */

	}


	.custom-dateText {
		display: flex;
		margin: 20px;
		justify-content: flex-end;

		/* 子元素居左 */
	}

	.custom-text3 {
		padding-left: 10px;
		color: #0055ff;
		font-size: 16px;

		font-weight: bold;
		padding-right: 10px;

	}

	/* 优化后的样式 */
	.optimized-table {
		font-size: 14px;
		border: 1px solid #ebeef5;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
	}

	.header-cell {
		background-color: #f5f7fa !important;
		color: #303133;
		font-weight: 600;
		padding: 12px 8px;
	}

	.body-cell {
		padding: 10px 8px;
		color: #606266;
		line-height: 1.5;
	}

	.table-row:hover {
		background-color: #fafafa;
	}

	.even-row {
		background-color: #fafafa;
	}

	.odd-row {
		background-color: #ffffff;
	}

	.address-text {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.status-cell {
		min-width: 80px;
	}

	.pagination-container {
		margin-top: 20px;
		padding: 12px;
		background: #fff;
		border-radius: 8px;
		display: flex;
		justify-content: flex-end;
	}

	/* 移动端适配 */
	@media screen and (max-width: 768px) {
		.optimized-table {
			font-size: 12px;
		}

		.header-cell {
			padding: 8px 4px;
		}

		.body-cell {
			padding: 6px 4px;
		}

		.pagination-container {
			flex-wrap: wrap;
			justify-content: center;
		}
	}

	/* 添加选中行高亮样式 */
	.uni-table-tr.selected-row {
		background-color: #f5f7fa;
	}

	/* 添加行点击效果 */
	.uni-table-tr {
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.uni-table-tr:hover {
		background-color: #fafafa;
	}
</style>